<?php

namespace app\api\Service;

use app\common\library\Auth;
use app\common\library\Sms as Smslib;
use think\Validate;
use think\Config;
use think\Db;

class RepairService
{
    // 获取报修分类
    public static function getType()
    {
        $list = \app\admin\model\ReportType::where(['status'=>'normal'])
            ->order('weigh desc')->field('id,name')->select();
        return ['code' =>1,'msg'=>'查询成功','data'=>$list];
    }

    // 获取报修分类
    public static function setType($data)
    {
        $type = isset($data['type']) ? $data['type'] : 1;

        $list = \app\admin\model\RepairSet::where(['type'=>$type])
            ->field('name')->select();
        return ['code' =>1,'msg'=>'查询成功','data'=>$list];
    }

    // 获取报修分类
    public static function getProblem($data)
    {
        $type_id = $data['type_id'];
        if(!$type_id) return ['code' =>0,'msg'=>'参数错误','data'=>''];
        $list = \app\admin\model\RepairProblem::where(['type_id'=>$type_id,'status'=>'normal'])->order('weigh desc')->field('id,name')->select();
        return ['code' =>1,'msg'=>'查询成功','data'=>$list];
    }

    // 获取维修费用分类
    public static function getRepairFee()
    {
        $list = \app\admin\model\RepairFee::where(['status'=>'normal'])
            ->order('id desc')->field('id,title,value')->select();
        return ['code' =>1,'msg'=>'查询成功','data'=>$list];
    }

    // 创建订单
    public static function createOrder($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        
        // 防止重复提交
        //构建用户特定的请求时间键
        $requestKey = "last_request_time_{$user_id}";
        $lastRequestTime = Cache::get($requestKey);
        $currentTime = time();
    
        if ($lastRequestTime && ($currentTime - $lastRequestTime < 5)) {
            return ['code'=>0,'msg'=>"请求太频繁，请稍后再试", 'data'=>''];
        }
        // 更新最后一次请求时间
        Cache::set($requestKey, $currentTime);
        
        $province_id = $data['province_id'];
        $city_id = $data['city_id'];
        $area_id = $data['area_id'];
        $address = $data['address'];
        $address_lng = $data['address_lng'];
        $address_lat = $data['address_lat'];
        $mobile = $data['mobile'];
        $name = $data['name'];
        $reservation_time = $data['reservation_time'];
        $device_name = $data['device_name'];
        $device_model = $data['device_model'];
        $repair_type = $data['repair_type'];
        $title = $data['title'];
        $description = $data['description'];
        $annex = $data['annex'];
        $callout_fee = $data['callout_fee'];
        $inspection_fee = $data['inspection_fee'];
        $used_score = $data['used_score'];
        $user_coupon_id = isset($data['user_coupon_id']) ? $data['user_coupon_id'] : 0;
        $is_invoicing = isset($data['is_invoicing']) ? $data['is_invoicing'] : 0;
        if($is_invoicing == 1)  {
            $invoicing_fee = $data['invoicing_fee'];
        }else{
            $invoicing_fee = 0;
        }
        $amount = $data['amount'];

        if(!$province_id) return ['code'=>0,'msg'=>"请选择省份", 'data'=>''];
        if(!$city_id) return ['code'=>0,'msg'=>"请选择城市", 'data'=>''];
        if(!$area_id) return ['code'=>0,'msg'=>"请选择区县", 'data'=>''];
        if(!$address) return ['code'=>0,'msg'=>"请填写详细地址", 'data'=>''];
        if(!$address_lng || !$address_lat) return ['code'=>0,'msg'=>"地址经纬度无效", 'data'=>''];
        if(!$name) return ['code'=>0,'msg'=>"请填写姓名", 'data'=>''];
        if(!Validate::regex($mobile, "^1\d{10}$")) return ['code'=>0,'msg'=>"手机号不正确", 'data'=>''];
        if(!$reservation_time) return ['code'=>0,'msg'=>"请选择预约时间", 'data'=>''];
        if(!$device_name) return ['code'=>0,'msg'=>"请选择设备名称", 'data'=>''];
        if(!$device_model) return ['code'=>0,'msg'=>"请选择设备型号device_name", 'data'=>''];
        if(!$repair_type) return ['code'=>0,'msg'=>"请选择报修类型", 'data'=>''];
        if(!$title) return ['code'=>0,'msg'=>"请填写问题", 'data'=>''];
        if(!$description) return ['code'=>0,'msg'=>"请填写问题描述", 'data'=>''];
//        if(!$annex) return ['code'=>0,'msg'=>"请上传故障图片/视频", 'data'=>''];
        if(!$callout_fee) return ['code'=>0,'msg'=>"上门费用不为空", 'data'=>''];
        // if(!$inspection_fee) return ['code'=>0,'msg'=>"检修费用不为空", 'data'=>''];
        if( (floor($used_score) - $used_score) != 0) return ['code'=>0,'msg'=>"抵用积分必须为正整数", 'data'=>''];

        // 优惠劵判断
        if($user_coupon_id){
            $coupon_id = \app\admin\model\CouponUser::where(['id'=>$user_coupon_id,'user_id'=>$user_id,'status'=>1])->value('coupon_id');
            if(!$coupon_id) return ['code'=>0,'msg'=>'优惠劵参数无效','data'=>''];
            $coupon = \app\admin\model\Coupon::where(['id'=>$coupon_id,'expiretime'=>['>',time()],'deletetime'=>null])
                ->find();
            if(!$coupon) return ['code'=>0,'msg'=>'优惠劵不存在','data'=>''];
            if($coupon['type'] == 1){
                if($amount >= $coupon['reduction_amount']) $coupon_money = $coupon['discount_amount'];
            }elseif ($coupon['type'] == 2){
                $coupon_money = $amount;
            }
            if($coupon['type'] == 2 && $used_score) return ['code'=>0,'msg'=>'维修全免卷和积分不可同时使用','data'=>''];
        }else{
            $coupon_money = 0;
        }

        // 抵扣积分判断
        if($used_score){
            $offset_ratio = Config::get("site.offset_ratio");
            $conversion_ratio = Config::get("site.conversion_ratio");
            if($used_score > $auth->score) return ['code'=>0,'msg'=>'用户积分不足','data'=>''];
            $amount = $amount - $coupon_money;
            $max_score = bcmul(bcmul($amount, ($offset_ratio/100)),$conversion_ratio);
            if($used_score > $max_score) return ['code'=>0,'msg'=>"最多使用{$max_score}积分",'data'=>''];
            $score_money = bcdiv($used_score, $conversion_ratio);
        }else{
            $score_money = 0;
        }

        $payamount = bcsub(bcsub(bcadd(bcadd($callout_fee,$inspection_fee),$invoicing_fee),$score_money),$coupon_money);

        if($amount != $payamount) return ['code'=>0,'msg'=>"订单金额有误", 'data'=>''];
//        return $payamount;
        try{
            $order_no = getNewOrderNo(16);
            $params_order = [
                'order_no'      =>  $order_no,
                'type'  => 'repair',
                'user_id'      =>  $user_id,
                'province_id'      =>  $province_id,
                'city_id'      =>  $city_id,
                'area_id'      =>  $area_id,
                'address'      =>  $address,
                'address_lng'      =>  $address_lng,
                'address_lat'      =>  $address_lat,
                'mobile'      =>  $mobile,
                'name'      =>  $name,
                'reservation_time'      =>  $reservation_time,
                'amount'      =>  $amount,
                'payamount'    => $payamount,
            ];

            $res = \app\admin\model\Order::create($params_order);

            $params_repair = [
                'order_id'      =>  $res['id'],
                'device_name'      =>  $device_name,
                'device_model'      =>  $device_model,
                'repair_type'      =>  $repair_type,
                'title'      =>  $title,
                'description'      =>  $description,
                'annex'      =>  $annex,
                'callout_fee'      =>  $callout_fee,
                'inspection_fee'      =>  $inspection_fee,
                'used_score'      =>  $used_score,
                'user_coupon_id'      =>  $user_coupon_id,
                'coupon_money'      =>  $coupon_money,
                'is_invoicing'      =>  $is_invoicing,
                'invoicing_fee'      =>  $invoicing_fee,
            ];
            $ret = \app\admin\model\OrderRepair::create($params_repair);

            Db::commit();
            if($res && $ret){

                // 修改优惠劵状态
                \app\admin\model\CouponUser::where(['id'=>$user_coupon_id,'user_id'=>$user_id])->update
                (['usedtime'=>time(),'updatetime'=>time(),'status'=>2]);

                return ['code'=>1,'msg'=>'操作成功','data'=>['order_id'=>$res['id']]];
            }else{
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

    }
}